<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AssessmentQuestion;
use App\Models\UserAssessmentAnswer;
use App\Models\UserAbility;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;

class AssessmentController extends Controller
{
    /**
     * 获取评估问题
     */
    public function questions(Request $request)
    {
        $cacheKey = 'assessment_questions_active';
        
        $questions = Cache::remember($cacheKey, 3600, function () {
            return AssessmentQuestion::active()
                                   ->inRandomOrder()
                                   ->limit(10)
                                   ->get();
        });

        $formattedQuestions = $questions->map(function ($question) {
            $options = $question->options;
            $formattedOptions = [];
            
            // 转换选项格式以匹配前端期望
            if (is_array($options)) {
                foreach ($options as $key => $value) {
                    $formattedOptions[] = [
                        'value' => $key,
                        'label' => $value,
                    ];
                }
            }
            
            return [
                'id' => $question->id,
                'question_text' => $question->question_text,
                'question_type' => 'multiple_choice', // 统一为multiple_choice类型
                'category' => $question->type_name,
                'ability_type' => $question->question_type,
                'options' => $formattedOptions,
            ];
        });

        return $this->success($formattedQuestions, '获取评估问题成功');
    }

    /**
     * 提交评估答案
     */
    public function submitAssessment(User $user, Request $request)
    {
        // 检查是否为当前用户
        if ($user->id !== $request->user()->id) {
            return $this->error('无权为其他用户提交评估', 403);
        }

        // 检查是否已经完成过基准测试
        $existingBaseline = $user->abilities()->where('is_baseline', true)->first();
        if ($existingBaseline) {
            return $this->error('已经完成过初始能力测试', 400);
        }

        $validator = Validator::make($request->all(), [
            'answers' => 'required|array|min:1',
            'answers.*.question_id' => 'required|exists:assessment_questions,id',
            'answers.*.answer_value' => 'required|string|max:10',
            'duration' => 'nullable|integer',
            'completed_at' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return $this->error('答案数据验证失败', 422, $validator->errors());
        }

        try {
            $scores = [
                'breaking_ice' => 0,
                'empathy' => 0,
                'conversation_flow' => 0
            ];

            $counts = [
                'breaking_ice' => 0,
                'empathy' => 0,
                'conversation_flow' => 0
            ];

            // 处理每个答案
            foreach ($request->answers as $answerData) {
                $question = AssessmentQuestion::find($answerData['question_id']);
                if (!$question) continue;

                $score = $question->calculateScore($answerData['answer_value']);

                // 保存用户答案
                UserAssessmentAnswer::create([
                    'user_id' => $user->id,
                    'question_id' => $question->id,
                    'selected_option' => $answerData['answer_value'],
                    'score_earned' => $score
                ]);

                // 累计分数
                $questionType = $question->question_type;
                if (isset($scores[$questionType])) {
                    $scores[$questionType] += $score;
                    $counts[$questionType]++;
                }
            }

            // 计算平均分并转换为0-100分制
            foreach ($scores as $ability => $totalScore) {
                if ($counts[$ability] > 0) {
                    $scores[$ability] = min(100, round(($totalScore / $counts[$ability]) * 20)); // 假设单题最高5分
                } else {
                    $scores[$ability] = 50; // 默认分数
                }
            }

            // 创建用户能力记录
            $userAbility = UserAbility::create([
                'user_id' => $user->id,
                'breaking_ice' => $scores['breaking_ice'],
                'empathy' => $scores['empathy'],
                'conversation_flow' => $scores['conversation_flow'],
                'is_baseline' => true
            ]);

            return $this->success([
                'ability_scores' => [
                    'breaking_ice' => $userAbility->breaking_ice,
                    'empathy' => $userAbility->empathy,
                    'conversation_flow' => $userAbility->conversation_flow,
                    'total_score' => $userAbility->getTotalScore(),
                ],
                'radar_data' => $userAbility->getRadarData(),
                'weakest_ability' => $userAbility->getWeakestAbility(),
                'is_baseline' => true,
                'created_at' => $userAbility->created_at
            ], '能力评估完成');

        } catch (\Exception $e) {
            return $this->error('评估提交失败，请稍后重试', 500);
        }
    }
}